/*
 * @lc app=leetcode.cn id=92 lang=cpp
 *
 * [92] 反转链表 II
 */

#include <iostream>
#include <stack>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
  public:
    ListNode *reverseBetween(ListNode *head, int left, int right)
    {
        if (left == right) {
            return head;
        }
        ListNode *pre = head;
        ListNode *pre_node = head;
        ListNode *left_node = nullptr;
        ListNode *tmp = head;
        int index = 1;

        while (index <= right) {
            if (index == left - 1) {
                pre = tmp;
            }
            if (index == left) {
                left_node = tmp;
            }
            if (index >= left + 1) {
                ListNode *current_node = tmp;
                tmp = tmp->next;
                current_node->next = pre_node;
                pre_node = current_node;
                ++index;
                continue;
            }
            ++index;
            pre_node = tmp;
            tmp = tmp->next;
        }
        left_node->next = tmp;
        if (left != 1) {
            pre->next = pre_node;
        }

        return (left == 1) ? pre_node : head;
    }
};
// @lc code=end
